package com.exam.serviceimpl;

import com.exam.entity.FillQuestion;
import com.exam.entity.JudgeQuestion;
import com.exam.mapper.FillQuestionRepository;
import com.exam.service.FillQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class FillQuestionServiceImpl implements FillQuestionService {

    @Autowired
    private FillQuestionRepository fillQuestionRepository;

    @Override
    public FillQuestion addFillQuestion(FillQuestion fillQuestion) {
        // 查重逻辑
        if (checkDuplicate(fillQuestion)) {
            throw new IllegalArgumentException("Duplicate fill question exists!");
        }
        return fillQuestionRepository.save(fillQuestion);
    }

    @Override
    public FillQuestion updateFillQuestion(Long id, FillQuestion fillQuestion) {
        FillQuestion existing = fillQuestionRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Fill question not found!"));
        existing.setSubject(fillQuestion.getSubject());
        existing.setQuestion(fillQuestion.getQuestion());
        existing.setAnswer(fillQuestion.getAnswer());
        return fillQuestionRepository.save(existing);
    }

    @Override
    public void deleteFillQuestion(Long id) {
        if (!fillQuestionRepository.existsById(id)) {
            throw new IllegalArgumentException("Fill question not found!");
        }
        fillQuestionRepository.deleteById(id);
    }

    @Override
    public FillQuestion getFillQuestionById(Long id) {
        return fillQuestionRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Fill question not found!"));
    }

    @Override
    public List<FillQuestion> getAllFillQuestions() {
        return fillQuestionRepository.findAll();
    }

    @Override
    public boolean checkDuplicate(FillQuestion fillQuestion) {
        return fillQuestionRepository
                .findBySubjectAndQuestionAndAnswer(fillQuestion.getSubject(), fillQuestion.getQuestion(), fillQuestion.getAnswer())
                .isPresent();
    }

    @Override
    public void importFillQuestions(List<FillQuestion> fillQuestions) {
        for (FillQuestion fillQuestion : fillQuestions) {
            if (!checkDuplicate(fillQuestion)) {
                fillQuestionRepository.save(fillQuestion);
            }
        }
    }

    @Override
    public Page<FillQuestion> getAllFillQuestions(Pageable pageable) {
        return fillQuestionRepository.findAll(pageable);
    }
}